<template>
  <div class="login-container">
    <van-nav-bar fixed left-arrow @click-left="$router.back()" title="校园超市">
      <template #right>
        <van-icon @click="$router.push('/')" name="shop-o" size="20" />
      </template>
    </van-nav-bar>
    <img src="@/assets/imgs/logo.jpg" class="logo" />
    <van-form @submit="reg">
      <van-field
        :maxlength="11"
        :rules="[
          { required: true, message: '请输入手机号' },
          { pattern: telPattern, message: '请输入合法的手机号' },
        ]"
        v-model="phone"
        placeholder="请输入手机号"
      />
      <!-- <van-field :rules="[{ required: true, message: '请输入昵称' }]" v-model="nickname" placeholder="请输入昵称" /> -->
      <van-field
        :rules="[{ required: true, message: '请输入密码' }]"
        type="password"
        v-model="password"
        placeholder="请输入密码"
      />

      <van-field
        :rules="[{ required: true, message: '请确认密码' }]"
        type="password"
        v-model="password2"
        placeholder="请确认密码"
      />
      <van-button native-type="submit" block round type="primary"
        >立即注册</van-button
      >
    </van-form>

    <router-link class="link" to="/login"> 已有账号,立即登录 </router-link>
  </div>
</template>
    
<script>
import _ from "lodash";
import { showToast } from "vant";
import { inject, ref } from "vue";
import { useRouter } from "vue-router";
export default {
  setup() {
    // 默认账号和密码
    const phone = ref("");
    const nickname = ref("");
    const password = ref("");
    const password2 = ref("");
    const telPattern = /^1[3456789]\d{9}$/;
    const router = useRouter();
    const axios = inject("axios");

    const reg = _.debounce(function () {
      const { phone, nickname, password, password2 } = this;
      if (password !== password2) {
        return showToast("两次密码输入不一致");
      }
      axios
        .post("/login", {
          phone: phone.value,
          nickname: nickname.value,
          password: password.value,
        })
        .then((res) => {
          showToast(res.msg);
          if (res.code == 200) {
            // 自动跳转到登录页面
            router.push("/login");
          }
        });
    });

    return {
      phone,
      nickname,
      password,
      password2,
      telPattern,
      reg,
    };
  },
};
</script>
    
<style lang="scss">
.login-container {
  padding: 10px;

  .logo {
    width: 80px;
    height: 80px;
    display: block;
    margin: 40px auto;
  }

  h3 {
    font-size: 30px;
    color: #444;
    font-weight: normal;
    margin: 30px 0;
    text-align: center;
  }

  .van-cell {
    background: #f2f2f2;
    border-radius: 20px;
    margin: 20px 0;
  }

  .link {
    margin: 15px;
    font-size: 14px;
    display: block;
    color: #333;
    text-align: center;
  }
}
</style>